<template>
  <header class="border-b border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
    <div class="flex items-center justify-between h-16 px-4 lg:px-6">
      <!-- 左侧：Logo和菜单切换 -->
      <div class="flex items-center space-x-4">
        <!-- 菜单切换按钮 -->
        <button
          v-if="showMenuToggle"
          @click="toggleSidebar"
          class="p-2 rounded-[0.6rem] text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all duration-200 active:scale-[0.985]"
          style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
        >
          <i class="icon-[heroicons--bars-3] w-5 h-5"></i>
        </button>
        
        <!-- Logo -->
        <div class="flex items-center space-x-3">
          <img 
            v-if="logo" 
            :src="logo" 
            :alt="title"
            class="h-8 w-8"
          >
          <div v-else class="h-8 w-8 bg-blue-500 rounded-[0.6rem] flex items-center justify-center">
            <i class="icon-[heroicons--academic-cap] w-5 h-5 text-white"></i>
          </div>
          
          <h1 v-if="title" class="text-lg font-semibold text-gray-900 hidden sm:block">
            {{ title }}
          </h1>
        </div>
      </div>

      <!-- 中间：面包屑导航 -->
      <div v-if="breadcrumbs.length" class="hidden md:flex items-center space-x-2 text-sm text-gray-500">
        <template v-for="(crumb, index) in breadcrumbs" :key="index">
          <router-link
            v-if="crumb.to && index < breadcrumbs.length - 1"
            :to="crumb.to"
            class="breadcrumb-item"
          >
            {{ crumb.title }}
          </router-link>
          <span v-else :class="{ 'text-gray-900 font-medium': index === breadcrumbs.length - 1 }">
            {{ crumb.title }}
          </span>
          <i 
            v-if="index < breadcrumbs.length - 1" 
            class="icon-[heroicons--chevron-right] w-4 h-4 breadcrumb-separator"
          ></i>
        </template>
      </div>

      <!-- 右侧：用户操作区 -->
      <div class="flex items-center space-x-4">
        <!-- 通知 -->
        <div v-if="showNotifications" class="relative">
          <button
            @click="toggleNotifications"
            class="p-2 rounded-[0.6rem] text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 relative transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <i class="icon-[heroicons--bell] w-5 h-5"></i>
            <span 
              v-if="unreadCount > 0" 
              class="absolute -top-1 -right-1 h-4 w-4 bg-red-500 text-white text-xs rounded-full flex items-center justify-center"
            >
              {{ unreadCount > 99 ? '99+' : unreadCount }}
            </span>
          </button>
          
          <!-- 通知下拉菜单 -->
          <div 
            v-if="showNotificationDropdown"
            class="absolute right-0 mt-2 w-80 rounded-[0.6rem] border border-gray-200 z-50"
            style="background-color: #FAF9F5; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);"
          >
            <div class="p-4 border-b border-gray-200">
              <div class="flex items-center justify-between">
                <h3 class="text-sm font-medium text-gray-900">通知</h3>
                <button 
                  v-if="unreadCount > 0"
                  @click="markAllAsRead"
                  class="text-xs text-blue-600 hover:text-blue-700"
                >
                  全部已读
                </button>
              </div>
            </div>
            
            <div class="max-h-64 overflow-y-auto">
              <div 
                v-for="notification in notifications.slice(0, 5)" 
                :key="notification.id"
                :class="[
                  'p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer',
                  { 'bg-blue-50': !notification.read }
                ]"
                @click="markAsRead(notification.id)"
              >
                <div class="flex items-start space-x-3">
                  <div :class="[
                    'w-2 h-2 rounded-full mt-2',
                    notification.read ? 'bg-gray-300' : 'bg-blue-500'
                  ]"></div>
                  <div class="flex-1 min-w-0">
                    <p class="text-sm font-medium text-gray-900 truncate">
                      {{ notification.title }}
                    </p>
                    <p class="text-sm text-gray-500 truncate">
                      {{ notification.message }}
                    </p>
                    <p class="text-xs text-gray-400 mt-1">
                      {{ formatTime(notification.createdAt) }}
                    </p>
                  </div>
                </div>
              </div>
              
              <div v-if="!notifications.length" class="p-4 text-center text-gray-500">
                暂无通知
              </div>
            </div>
          </div>
        </div>

        <!-- 主题切换 -->
        <button
          v-if="showThemeToggle"
          @click="toggleTheme"
          class="p-2 rounded-lg text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <i :class="isDark ? 'icon-[heroicons--sun]' : 'icon-[heroicons--moon]'" class="w-5 h-5"></i>
        </button>

        <!-- 用户菜单 -->
        <div class="relative">
          <button
            @click="toggleUserMenu"
            class="flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <img
              v-if="userInfo?.avatar"
              :src="userInfo.avatar"
              :alt="userInfo.name"
              class="h-8 w-8 rounded-full object-cover"
            >
            <div v-else class="h-8 w-8 bg-blue-500 rounded-full flex items-center justify-center">
              <i class="icon-[heroicons--user] w-4 h-4 text-white"></i>
            </div>
            
            <div class="hidden sm:block text-left">
              <p class="text-sm font-medium text-gray-900">{{ userInfo?.name || '用户' }}</p>
              <p class="text-xs text-gray-500">{{ roleText }}</p>
            </div>
            
            <i class="icon-[heroicons--chevron-down] w-4 h-4 text-gray-500"></i>
          </button>
          
          <!-- 用户下拉菜单 -->
          <div 
            v-if="showUserDropdown"
            class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50"
          >
            <div class="p-2">
              <router-link
                v-for="item in userMenuItems"
                :key="item.key"
                :to="item.to"
                class="flex items-center space-x-2 px-3 py-2 text-sm text-gray-700 rounded-lg hover:bg-gray-100"
                @click="showUserDropdown = false"
              >
                <i :class="item.icon" class="w-4 h-4"></i>
                <span>{{ item.label }}</span>
              </router-link>
              
              <hr class="my-2 border-gray-200">
              
              <button
                @click="handleLogout"
                class="flex items-center space-x-2 w-full px-3 py-2 text-sm text-red-600 rounded-lg hover:bg-red-50"
              >
                <i class="icon-[heroicons--arrow-right-on-rectangle] w-4 h-4"></i>
                <span>退出登录</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, defineProps } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/auth'
import { useAppStore } from '../../stores/app'
import dayjs from 'dayjs'

// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: '新生报到服务平台'
  },
  logo: {
    type: String,
    default: ''
  },
  showMenuToggle: {
    type: Boolean,
    default: true
  },
  showNotifications: {
    type: Boolean,
    default: true
  },
  showThemeToggle: {
    type: Boolean,
    default: true
  }
})

// 使用stores
const authStore = useAuthStore()
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const showNotificationDropdown = ref(false)
const showUserDropdown = ref(false)

// 计算属性
const userInfo = computed(() => authStore.userInfo)
const breadcrumbs = computed(() => appStore.breadcrumbs)
const notifications = computed(() => appStore.notifications)
const unreadCount = computed(() => appStore.unreadNotifications)
const isDark = computed(() => appStore.isDark)

const roleText = computed(() => {
  const roleMap = {
    admin: '管理员',
    student: '学生',
    teacher: '教师'
  }
  return roleMap[authStore.userRole] || '用户'
})

const userMenuItems = computed(() => {
  const baseItems = [
    {
      key: 'profile',
      label: '个人资料',
      icon: 'icon-[heroicons--user-circle]',
      to: authStore.isAdmin ? '/admin/profile' : '/student/profile'
    },
    {
      key: 'settings',
      label: '设置',
      icon: 'icon-[heroicons--cog-6-tooth]',
      to: authStore.isAdmin ? '/admin/settings' : '/student/settings'
    }
  ]
  
  if (authStore.isAdmin) {
    baseItems.unshift({
      key: 'dashboard',
      label: '管理后台',
      icon: 'icon-[heroicons--squares-2x2]',
      to: '/admin/dashboard'
    })
  }
  
  return baseItems
})

// 方法
const toggleSidebar = () => {
  appStore.toggleSidebar()
}

const toggleNotifications = () => {
  showNotificationDropdown.value = !showNotificationDropdown.value
  showUserDropdown.value = false
}

const toggleUserMenu = () => {
  showUserDropdown.value = !showUserDropdown.value
  showNotificationDropdown.value = false
}

const toggleTheme = () => {
  appStore.toggleTheme()
}

const markAsRead = (id) => {
  appStore.markNotificationAsRead(id)
}

const markAllAsRead = () => {
  appStore.markAllNotificationsAsRead()
}

const formatTime = (time) => {
  return dayjs(time).fromNow()
}

const handleLogout = async () => {
  showUserDropdown.value = false
  await authStore.logout()
  
  // 根据用户角色跳转到对应登录页
  const loginPath = authStore.userRole === 'admin' ? '/admin/login' : '/student/login'
  router.push(loginPath)
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.relative')) {
    showNotificationDropdown.value = false
    showUserDropdown.value = false
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
/* 组件特定样式 */
</style>